#导入数据库模块
from datetime import timedelta

import pymysql
# import pywsgi
#导入Flask框架，这个框架可以快捷地实现了一个WSGI应用
from flask import Flask
#默认情况下，flask在程序文件夹中的templates子文件夹中寻找模块
from flask import render_template
#导入前台请求的request模块
from flask import Flask, render_template, request, redirect, url_for,jsonify,session
import traceback


from entity import Exercise_fill,Student_exercise,Exercise_Select
from dbProcess import dbProcess
dbProcess = dbProcess()#数据库操作类
#传递根目录
app = Flask(__name__)

# #会话保存当前用户信息
# session['local_user'] = '贺步贵'
# session['local_id'] = 1
# session['local_password'] = '157352asd'
# 要用session，必须app配置一个密钥
app.secret_key  =  "lyc"
app.config['SESSION_COOKIE_NAME']="session_key"  #这是配置网页中sessions显示的key
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(seconds=2000)  # 配置20秒有效

@app.route('/draft')
def test():
    return render_template('draft.html')

'''学习园地'''
@app.route('/study')
def study():
    user = session.get('local_user')
    pwd = session.get('local_password')
    print("用户信息: ",user,pwd)
    results = dbProcess.query_all_exercises(table='exercise_fill')
    print(results)
    exercises = []
    for result in results:
        exercise = {
            'id':result[0],
            'name':result[1],
            'master_level':"良好",
            'type':"填空题",
        }
        exercises.append(exercise)

    results2 = dbProcess.query_all_exercises(table='exercise_select_demo')
    print(results2)
    select_exercises = []
    for result in results2:
        select_exercise = {
            'id':result[0],
            'name':result[1][:10],
            'master_level':"良好",
            'KC':result[4],
        }
        select_exercises.append(select_exercise)
    return render_template('study.html',exercises=exercises,select_exercises=select_exercises,local_user=user)

@app.route('/')
def login():
    return render_template('login.html')

#默认路径访问注册页面
@app.route('/regist')
def regist():
    return render_template('regist.html')

#获取注册请求及处理
@app.route('/registuser')
def getRigistRequest():
    #把用户名和密码注册到数据库中
    user = request.args.get('user')
    pwd = request.args.get('password')
    if dbProcess.regist_user(user,pwd):
        return render_template('login.html')
    else:
        return '注册失败' #返回一个页面

'''习题推荐'''
@app.route('/recommend')
def recommend():
    return render_template('recommend.html')

def regist():
    return render_template('regist.html')


'''学情分析'''
# 获取登录参数及处理
@app.route('/login',methods=['POST','GET'])
def getLoginRequest():
    # 查询用户名及密码是否匹配及存在
    # 连接数据库,此前在数据库中创建数据库ktsys
    user = request.values.get('user')
    pwd = request.values.get('password')
    print(user,pwd)
    if dbProcess.query_one_user(user,pwd)!=-1:
        # 登录成功，保存登录用户信息
        session['local_user'] = user
        session['local_password'] = pwd
        session['local_id'] = dbProcess.query_one_user(user,pwd)[0][0]# 用户id
        user_id = 64525
        exercise_num, exercise_correct_num, exercise_incorrect_num = dbProcess.get_basic_info(user_id)  # 获取基本信息
        rate = round(exercise_correct_num / exercise_num, 4) * 100
        rank = 1
        total_students = 30
        often_exercises = ['函数','类与对象','基本数据类型',]
        last_exercise_time = '2024-2-28'
        return render_template('analysis.html', user_id=user_id, exercise_num=exercise_num,
                               exercise_correct_num=exercise_correct_num,
                               exercise_incorrect_num=exercise_incorrect_num, rate=rate, rank=rank,
                               total_students=total_students, often_exercises=often_exercises,
                               last_exercise_time=last_exercise_time)
    else:
        # 登录成功，保存登录用户信息
        session['local_user'] = user
        session['local_password'] = pwd
        session['local_id'] = dbProcess.query_one_user(user, pwd)[0][0]  # 用户id
        user_id = 64525
        exercise_num, exercise_correct_num, exercise_incorrect_num = dbProcess.get_basic_info(user_id)  # 获取基本信息
        rate = round(exercise_correct_num / exercise_num, 4) * 100
        rank = 1
        total_students = 30
        often_exercises = ['圆周率']
        last_exercise_time = '2019-5-12'
        return render_template('analysis.html', user_id=user_id, exercise_num=exercise_num,
                               exercise_correct_num=exercise_correct_num,
                               exercise_incorrect_num=exercise_incorrect_num, rate=rate, rank=rank,
                               total_students=total_students, often_exercises=often_exercises,
                               last_exercise_time=last_exercise_time)
    return '登录失败'



# 处理ajax请求
@app.route('/testGet',methods=['GET'])
def testGet():
    id = request.args.get('id')#获取ajax参数
    print("正在请求id为：" + id + "的练习题")#打印
    #数据库查询练习题信息
    result = dbProcess.query_exercises_by_id(table='exercise_fill',id=id)
    print(id)
    print(type(result[0]),result[0])
    exercise = Exercise_fill(id,result[0][1],result[0][2],result[0][3],result[0][4],result[0][5])
    print(exercise.tostring())#打印
    return jsonify({'id':exercise.id,'content':exercise.content, 'object':exercise.object,'measure':exercise.measure})#返回值

@app.route('/SelectGet',methods=['GET'])
def SelectGet():
    id = request.args.get('id')#获取ajax参数
    print("正在请求id为：" + id + "的练习题")#打印
    #数据库查询练习题信息
    result = dbProcess.query_exercises_by_id(table='exercise_select',id=id)
    print(result)
    exercise = Exercise_Select(id,content=result[0][1],type=result[0][2],answer=result[0][3],KC=result[0][4],name=result[0][1])
    print(exercise.tostring())#打印
    return jsonify({'id':exercise.id,'content':exercise.content})#返回值

'''填空题检查，并生成练习记录'''
@app.route('/checkAnswer',methods=['POST','GET'])
def checkAnswer():
    id = request.values.get('id')  # 接收参数
    user_answer = request.values.get('user_answer')#接收参数
    end_time = request.values.get('end_time')#接收参数
    print("时间为： ",end_time)
    # id=6
    print(id,user_answer)
    result = dbProcess.query_answer_by_id(table='exercise_fill',id=id)
    print(result)
    flag =(str(user_answer) == result[0][5])
    student_exercise = Student_exercise(None,session.get('local_id'),id,int(flag),end_time)
    # print(student_exercise.tostring())
    dbProcess.insert_student_exercise(student_exercise)
    if flag:
        return jsonify({'status':'答案正确'})
    else:
        return jsonify({'status':'答案错误'})

'''选择题检查，并生成练习记录'''
@app.route('/checkSelectAnswer',methods=['POST','GET'])
def checkSelectAnswer():
    id = request.values.get('id')  # 接收参数
    user_answer = request.values.get('user_answer')#接收参数
    end_time = request.values.get('end_time')#接收参数
    print("时间为： ",end_time)
    # id=6
    print(id,user_answer)
    result = dbProcess.query_answer_by_id(table='exercise_select', id=id)
    print(result[0][3])
    '''大小写适配'''
    flag = (str(user_answer).lower() == result[0][3].lower())
    # print(str(user_answer),str(user_answer).lower())
    # print(result[0][3],result[0][3].lower())
    student_exercise = Student_exercise(None, session.get('local_id'), id, int(flag), end_time)
    print(student_exercise.tostring())
    if flag:
        return jsonify({'status': '答案正确'})
    else:
        return jsonify({'status': '答案错误'})



# 使用__name__ == '__main__'是 Python 的惯用法，确保直接执行此脚本时才
# 启动服务器，若其他程序调用该脚本可能父级程序会启动不同的服务器
if __name__ == '__main__':
    app.run(debug=True)
